//////////////////
#include "stdafx.h"
#include "FileUtils.h"

using namespace std;

std::vector<std::string> listFiles(const std::string &srcPath, const std::string &rootPath)
{
	_finddata_t fileInfo;
	std::vector<std::string> fileList;
	std::string findPath = srcPath + "*";
	long handle = _findfirst(findPath.c_str(), &fileInfo);

	if (handle == -1L)
		return fileList;

	do {
		if (fileInfo.attrib & _A_SUBDIR) {
			if (fileInfo.name[0] != '.') {
				std::string subFilePath = srcPath + fileInfo.name + "\\";
				for (auto filename : listFiles(subFilePath, rootPath)) fileList.push_back(filename);
			}
		}
		else {
			std::string subFilePath = srcPath + fileInfo.name;
			subFilePath.replace(0, rootPath.length(), "");
			std::transform(subFilePath.begin(), subFilePath.end(), subFilePath.begin(), ::tolower);
			fileList.push_back(subFilePath);
		}
	} while (_findnext(handle, &fileInfo) == 0);

	_findclose(handle);
	return fileList;
}

string getFileExtName(const string &path) {
	int idx = path.rfind('.');
	if (idx == -1) return "";
	string ext = path.substr(idx + 1);
	std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
	return ext;
}

bool assurePathExisted(const string &filePath) {
	string path = filePath;
	if (path.at(path.length() - 1) != '\\') {
		int n = path.rfind('\\');
		if (n != -1) {
			path = path.substr(0, n);
		}
	}

	char str[512];
	strncpy(str, path.c_str(), sizeof(str));
	int len = strlen(str);
	for (int i = 0; i<len; i++) {
		if (str[i] == '\\') {
			str[i] = '\0';
			if (_access(str, 0) != 0) {
				_mkdir(str);
			}
			str[i] = '\\';
		}
	}
	if (len > 0 && _access(str, 0) != 0) {
		_mkdir(str);
	}
	return true;
}
